package cn.changeforyou.web.dao.mybatis.ext.extBuilder.writer;

import cn.changeforyou.web.dao.mybatis.ext.dao.BaseDao;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.SqlContext;
import cn.changeforyou.web.dao.mybatis.ext.extBuilder.sqlUtils.ONGLUtils;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.EntityMetaInfo;
import cn.changeforyou.web.dao.mybatis.ext.metaInfo.FieldMetaInfo;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhyu
 * @version 1.0
 * @date 2022/3/11 6:55
 */
@Component
public class InsertEntityListSqlWriter extends AbstractSqlWriter {

    @Override
    void doWriteSql(SqlContext context) {
        EntityMetaInfo insertMetaInfo = context.getInsertMetaInfo();
        SqlBuilder sql = context.getSql();
        String tableName = insertMetaInfo.getTableName();
        sql.append("<script>\n");
        sql.append(" INSERT INTO ").append(tableName).append(" (");
        List<FieldMetaInfo> fieldMetaInfoList = insertMetaInfo.getFieldMetaInfoList();
        for (int i = 0; i < fieldMetaInfoList.size(); i++) {
            FieldMetaInfo metaInfo = fieldMetaInfoList.get(i);
            String columnName = metaInfo.getColumnName();

            if (i != 0) {
                sql.append(",");
            }
            sql.append(" ").append(columnName);
        }
        sql.append(") VALUES ");
        //<foreach collection="usersList" item="model" separator=",">     </foreach>
        sql.append("\n<foreach collection=\"").append(BaseDao.LIST).append("\" item=\"item\"  separator=\",\">");
        sql.append("\n(");
        for (int i = 0; i < fieldMetaInfoList.size(); i++) {
            FieldMetaInfo metaInfo = fieldMetaInfoList.get(i);
            String fieldName = metaInfo.getFieldName();
            if( i != 0) {
                sql.append(",");
            }
            ONGLUtils.buildMybatisVar(fieldName, "item", sql);
        }
        sql.append("\n)");
        sql.append("\n</foreach>");
        sql.append("\n</script>");
    }

    @Override
    public SentenceEnum getSentenceEnum() {
        return SentenceEnum.insert;
    }
}
